package com.fzy.leetcode.editor.cn;
//2023-03-22 14:52:36
//给定两个整数数组 preorder 和 inorder ，其中 preorder 是二叉树的先序遍历， inorder 是同一棵树的中序遍历，请构造二叉树并
//返回其根节点。 
//
// 
//
// 示例 1: 
// 
// 
//输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//输出: [3,9,20,null,null,15,7]
// 
//
// 示例 2: 
//
// 
//输入: preorder = [-1], inorder = [-1]
//输出: [-1]
// 
//
// 
//
// 提示: 
//
// 
// 1 <= preorder.length <= 3000 
// inorder.length == preorder.length 
// -3000 <= preorder[i], inorder[i] <= 3000 
// preorder 和 inorder 均 无重复 元素 
// inorder 均出现在 preorder 
// preorder 保证 为二叉树的前序遍历序列 
// inorder 保证 为二叉树的中序遍历序列 
// 
//
// Related Topics 树 数组 哈希表 分治 二叉树 👍 1904 👎 0

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class ConstructBinaryTreeFromPreorderAndInorderTraversal {
    public static void main(String[] args) {
        //创建该题目的对象方便调用
        Solution solution = new ConstructBinaryTreeFromPreorderAndInorderTraversal().new Solution();
    }
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    Map<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();

        for(int i = 0;i< preorder.length;i++){
            map.put(inorder[i],i);
        }

        return dfs(preorder,0,preorder.length,inorder,0, inorder.length);
    }

    public TreeNode dfs(int[] preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd){
        if(preStart>=preEnd || inStart>=inEnd){
            return null;
        }

        int rootIdx = map.get(preorder[preStart]);  //找到前序遍历的第一个元素在中序遍历中的位置
        TreeNode node = new TreeNode(inorder[rootIdx]);

        int lenOfLeft = rootIdx - inStart;      //保存中序左子树个数，用来确定前序数列的个数

        node.left = dfs(preorder,preStart+1,preStart+lenOfLeft+1,inorder,inStart,rootIdx);
        node.right = dfs(preorder,preStart+lenOfLeft+1,preEnd,inorder,rootIdx+1,inEnd);

        return node;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}